import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import('../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/User.vue'),
    redirect: "/user/cart",
    children: [
      {
        path: "cart",
        component: () => import("../components/user/Cart.vue"),
      },
    ],
    // //独享守卫
    // beforeEnter: (to, from, next) => {
    //   // ...
    //   console.log("独享守卫",to,from);
    //   let token = localStorage.getItem("x-auth-token");
    //   if (token) {
    //     next();
    //   } else {
    //     // alert('宝贝，请先登录哦！')
    //     store.dispatch("showToast/asyncChangeIsShowToast", {
    //       isShow: true,
    //       msg: '请先登录！！！',
    //       type: 'danger'
    //     })
    //   }
    // },

  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import('../views/Free.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import('../views/Details.vue')
  },
  // {
  //   path: '*',
  //   name: 'error',
  //   component: () => import('../components/Error.vue')
  // },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//全局守卫
// router.beforeEach((to, from, next) => {
//   // to: Route: 即将要进入的目标 路由对象
//   // from: Route: 当前导航正要离开的路由
//   // next: Function: 一定要调用该方法来 resolve 这个钩子。
//   console.log("全局守卫",to,from);
//   if(to.path=="/user/cart"){
//     let token = localStorage.getItem("x-auth-token");
//     if(token){
//       next();
//     }else{
//       // alert('宝贝，请先登录哦！')
//       store.dispatch("showToast/asyncChangeIsShowToast",{
//         isShow:true,
//         msg:'请先登录！！！',
//         type:'danger'
//       })
//     }
//   }else{
//     next();//如果没有执行这个函数，则看不见当前页面
//   }
// })

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};

export default router
